package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@Slf4j
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 将图片上传到minio中
        // 原文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 后缀名
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 新文件名
        String fileName = UUID.randomUUID().toString().replace("-", "") + postfix;
        String imgPath = null;
        try {
            imgPath = fileStorageService.uploadImgFile("", fileName,
                    multipartFile.getInputStream());
        } catch (IOException e) {
            return ResponseResult.errorResult(501, "文件上传失败");
        }
        // 将图片路径保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        // 从当前线程中获取userId
        Integer userId = WmThreadLocalUtil.getUser().getId();
        wmMaterial.setUserId(userId);
        wmMaterial.setUrl(imgPath);
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        // 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 图片列表
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult getMaterialList(WmMaterialDto wmMaterialDto) {
        // 检查参数
        wmMaterialDto.checkParam();
        Short isCollection = wmMaterialDto.getIsCollection();
        // 分页查询
        IPage<WmMaterial> page = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        // 执行方法
        page = page(page, Wrappers.<WmMaterial>lambdaQuery()
                .eq(isCollection != null && isCollection == 1, WmMaterial::getIsCollection,
                        isCollection)
                .eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .orderByDesc(WmMaterial::getCreatedTime));
        // 返回结果
        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(),
                wmMaterialDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 图片删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deletePicture(Integer id) {
        // 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 查询方法
        WmMaterial wmMaterial = getOne(Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getUserId,WmThreadLocalUtil.getUser().getId())
                .eq(WmMaterial::getId,
                id));
        // 查询失败
        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 如果图片在素材中引用，不能删除
        List<WmNewsMaterial> wmNewsMaterialList =
                wmNewsMaterialMapper.selectList(Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getMaterialId, wmMaterial.getId()));
        if (wmNewsMaterialList!=null && wmNewsMaterialList.size() > 0) {
            return ResponseResult.errorResult(501,"图片在素材中引用，不能删除");
        }
        // 删除minio里的图片
        fileStorageService.delete(wmMaterial.getUrl());
        // 删除数据库的信息
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 图片收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectPicture(Integer id) {
        // 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 执行方法
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 1));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        // 参数校验
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 执行方法
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .eq(WmMaterial::getId, id)
                .set(WmMaterial::getIsCollection, 0));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
